package net.pimpas.web.jsf.components.simplemenu.impl;

import java.util.ArrayList;
import java.util.List;

import net.pimpas.util.reflection.ReflectionUtil;
import net.pimpas.web.jsf.components.simplemenu.SimpleMenu;
import net.pimpas.web.jsf.components.simplemenu.SimpleMenuElement;
import net.pimpas.web.jsf.components.simplemenu.SimpleMenuItem;

public class SimpleMenuImpl extends SimpleMenuElementImpl implements SimpleMenu {

	private static final long serialVersionUID = 8161137865184691105L;
	
	private List<SimpleMenuElement> children;
	
	public SimpleMenuImpl(String name) {
		super(name);
		this.setChildren(new ArrayList<SimpleMenuElement>());
	}

	public void addChild(SimpleMenuElement element) {
		this.getChildren().add(element);
	}

	public List<SimpleMenuElement> getChildren() {
		return this.children;
	}

	public void removeChild(SimpleMenuElement element) {
		if(this.getChildren().contains(element)) this.getChildren().remove(element);
	}

	public void setChildren(List<SimpleMenuElement> children) {
		this.children = children;
	}
	
	@Override
	public String toString() {
		StringBuffer buff = new StringBuffer();
		buff.append("var "+this.getName()+ " = new simpleMenu;");
		SimpleMenuItem smi = null;
		for(int i=0;i<this.getChildren().size();i++) {
			buff.append(this.getChildren().get(i).toString());
			if(ReflectionUtil.isSubclass(this.getChildren().get(i).getClass(), SimpleMenuItem.class))
				buff.append(this.getName()+".add("+this.getChildren().get(i).getName()+");");
			else if(ReflectionUtil.isSubclass(this.getChildren().get(i).getClass(), SimpleMenu.class)) {
				smi = new SimpleMenuItemImpl(this.getChildren().get(i).getName()+"_item_access");
				smi.setLabel(this.getChildren().get(i).getLabel());
				smi.setTooltip(this.getChildren().get(i).getTooltip());
				smi.setIcon(this.getChildren().get(i).getIcon());
				smi.setIconHover(this.getChildren().get(i).getIconHover());
				smi.setParent(this.getChildren().get(i));
				buff.append(smi);
				buff.append(this.getName()+".add("+smi.getName()+");");
			}
		}
		
		return new String(buff);
	}
}